import {exportBaseUrl, request} from '@/utils/request'
import {getUploadKey} from "@/api/public";

/* 上图 */
export function picUpload(that, uploadFileList, callback) {
    getUploadKey({
        type: that.picType
    }, tokenRes => {
        let form = new FormData();
        uploadFileList.filter(uploadFile => uploadFile.file).forEach(uploadFile => {
            form.append("files", uploadFile.file);
            uploadFile.status = "uploading";
            uploadFile.message  = "上传中...";
        });

        that.$toast.loading({
            message: '加载中...',
            forbidClick: true,
            duration: 60000,
            loadingType: 'spinner'
        });

        let oReqCos = new XMLHttpRequest();
        oReqCos.open('POST', exportBaseUrl("res") + '/file_upload/upload_pic');
        oReqCos.setRequestHeader('x-yd-access-token', tokenRes.accessToken);
        oReqCos.onload = function () {
            if (oReqCos.status === 200) {
                let res = JSON.parse(oReqCos.response);
                if (res.code === 2000) {
                    callback(res);
                } else {
                    uploadFileList.forEach(uploadFile => {
                        uploadFile.status = "done";
                    });
                    that.$toast.fail(res.msg);
                }
            } else {
                that.$toast.fail("未知原因");
            }
        }

        oReqCos.send(form);
    });
}

/* 随机颜色 */
export function randomColor(num) {
    // 1 代表获取 浅色的随机色    2代表获取深色的随机色   不传参数num代表获取随机色
    let arr = [];
    for (let i = 0; i < 3; i++) {
        if(1 == num) {
            // 暖色
            arr.push(Math.floor(Math.random() * 128 + 24));
            // 亮色
            // arr.push(Math.floor(Math.random() * 128 + 128));
        } else if(2 == num) {
            // 暗色
            arr.push(Math.floor(Math.random() * 128));
            // 暗黑色
            // arr.push(Math.floor(Math.random() * 64));
        } else {
            arr.push(Math.floor(Math.random() * 256));
        }
    }
    let [r, g, b] = arr;
    // rgb颜色
    // var color=`rgb(${r},${g},${b})`;
    // 16进制颜色
    let color = `#${r.toString(16).length > 1 ? r.toString(16) : '0' + r.toString(16)}${g.toString(16).length > 1 ? g.toString(16) : '0' + g.toString(16)}${
        b.toString(16).length > 1 ? b.toString(16) : '0' + b.toString(16)}`;
    return color;
}